package com.lbj.mall.cart.interceptor;

import com.lbj.mall.cart.entity.to.UserInfoTo;
import com.lbj.mall.common.constant.APPConstant;
import com.lbj.mall.common.entity.vo.MemberVo;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 购物车拦截器
 */
@Component // 拦截器也是一个组件，必须放到容器中
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /**
     * 在方法之前执行，返回true表示放行，返回false不傲视不放行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        UserInfoTo to = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberVo memberVo = (MemberVo) session.getAttribute(APPConstant.SAVE_LOGIN_USER);
        // 用户登录
        if (memberVo != null) {
            to.setUserId(memberVo.getId());
        }
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(APPConstant.TEMP_USER_COOKIE_NAME)) {
                    to.setUserKey(cookie.getValue());
                }
            }
        }
        // 一定要保证接口获取到的user-key不能为空
        // 所以这里判断，当user-key为空则重新创建一个
        if (StringUtils.isEmpty(to.getUserKey())) {
            to.setUserKey(UUID.randomUUID().toString());
        }
        threadLocal.set(to);
        return true;
    }

    /**
     * 在方法之后执行：通知浏览器保存一个cookie
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        if (!StringUtils.isEmpty(userInfoTo.getUserKey())) {
            Cookie cookie = new Cookie(APPConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("localmall.com");
            cookie.setMaxAge(APPConstant.MONTH_SECOND);
            response.addCookie(cookie);
        }
    }
}


